/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

import controller.CategoriaController;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import model.CategoriaMODEL;
import table.CellRenderer;
import table.TooltipCellRender;
import table.categoria.CategoriaTable;

/**
 *
 * @author Welisson
 */
public class Categorias extends javax.swing.JDialog {
    private static final int VISUALIZAR = 0;
    private static final int ADCIONAR = 1;
    private static final int EDITAR = 2;
    private static final int SELECIONAR = 3;

    private int status = VISUALIZAR;
    private int linhaSelecionada = -1;

    private List<CategoriaMODEL> categorias;

    private JTable tblCategorias;
    private CategoriaTable tableModel;
    private JScrollPane scrollPane;
    /**
     * Creates new form Categorias
     */
    public Categorias(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        montaTabela();
        statusTela(status);
//        limiteJTextFields();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTCategoria = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMNovo = new javax.swing.JMenu();
        jMSalvar = new javax.swing.JMenu();
        jMEditar = new javax.swing.JMenu();
        jMExcluir = new javax.swing.JMenu();
        jMLimpar = new javax.swing.JMenu();
        jMCancelar = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Categoria:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTCategoria, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(39, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 159, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        jMenuBar1.setBackground(new java.awt.Color(51, 51, 51));
        jMenuBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jMenuBar1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N

        jMNovo.setForeground(new java.awt.Color(255, 255, 255));
        jMNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/Add.png"))); // NOI18N
        jMNovo.setText("Novo");
        jMNovo.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jMNovo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMNovoMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMNovo);

        jMSalvar.setForeground(new java.awt.Color(255, 255, 255));
        jMSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/Save.png"))); // NOI18N
        jMSalvar.setText("Gravar");
        jMSalvar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jMSalvar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMSalvarMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMSalvar);

        jMEditar.setForeground(new java.awt.Color(255, 255, 255));
        jMEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/Modify.png"))); // NOI18N
        jMEditar.setText("Alterar");
        jMEditar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jMEditar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMEditarMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMEditar);

        jMExcluir.setForeground(new java.awt.Color(255, 255, 255));
        jMExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/Close.png"))); // NOI18N
        jMExcluir.setText("Deletar");
        jMExcluir.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jMExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMExcluirMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMExcluir);

        jMLimpar.setForeground(new java.awt.Color(255, 255, 255));
        jMLimpar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/Undo.png"))); // NOI18N
        jMLimpar.setText("Limpar");
        jMLimpar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jMLimpar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMLimparMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMLimpar);

        jMCancelar.setForeground(new java.awt.Color(255, 255, 255));
        jMCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/Back.png"))); // NOI18N
        jMCancelar.setText("Cancelar");
        jMCancelar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jMCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMCancelarMouseClicked(evt);
            }
        });
        jMenuBar1.add(jMCancelar);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMNovoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMNovoMouseClicked
        if(jMNovo.isEnabled()){
            statusTela(ADCIONAR);
            jTCategoria.requestFocus();
        }
    }//GEN-LAST:event_jMNovoMouseClicked

    private void jMSalvarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMSalvarMouseClicked
        if(jMSalvar.isEnabled()){
            String categoria = jTCategoria.getText();
            if(categoria.trim().equals("")){
                JOptionPane.showMessageDialog(this, "Preencha o campo Categoria!");
            }else{
                if(status == ADCIONAR){
                    if(new CategoriaController().salvar(categoria,tableModel)){
                        JOptionPane.showMessageDialog(this, "Categoria Cadastrada com Sucesso!");
                    }else{
                        JOptionPane.showMessageDialog(this, "Erro ao cadastrar.\nTente novamente mais tarde!");
                    }
                    statusTela(VISUALIZAR);
                }else if(status == EDITAR){
                    if(new CategoriaController().editar(categorias.get(linhaSelecionada).getId(), categoria, tableModel, linhaSelecionada)){
                        JOptionPane.showMessageDialog(this, "Categoria Editada com Sucesso!");
                    }else{
                        JOptionPane.showMessageDialog(this, "Erro ao Editar.\nTente novamente mais tarde!");
                    }
                    statusTela(VISUALIZAR);
                }
            }
        }
    }//GEN-LAST:event_jMSalvarMouseClicked

    private void jMEditarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMEditarMouseClicked
        if(jMEditar.isEnabled()){
            linhaSelecionada = tblCategorias.getSelectedRow();
            jTCategoria.setText(categorias.get(linhaSelecionada).getCategoria());
            statusTela(EDITAR);
        }
    }//GEN-LAST:event_jMEditarMouseClicked

    private void jMExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMExcluirMouseClicked
        if(jMExcluir.isEnabled()){
            linhaSelecionada = tblCategorias.getSelectedRow();
            int excluir = JOptionPane.showConfirmDialog(this, "Deseja realmente Excluir esses Dados?", "Excluir", JOptionPane.YES_NO_OPTION);
            if (excluir == JOptionPane.YES_OPTION) {
                int id  = categorias.get(linhaSelecionada).getId();
                
                if(new CategoriaController().excluir(id, tableModel, linhaSelecionada)){
                    JOptionPane.showMessageDialog(this, "Categoria Excluida com Sucesso!");
                    statusTela(VISUALIZAR);
                }else{
                    JOptionPane.showMessageDialog(this, "Erro ao Excluir Funcionario!\n Tente Novamente mais tarde!");
                }
            }
        }
    }//GEN-LAST:event_jMExcluirMouseClicked

    private void jMLimparMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMLimparMouseClicked
        if(jMLimpar.isEnabled()){
            limpaCampos();
        }
    }//GEN-LAST:event_jMLimparMouseClicked

    private void jMCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMCancelarMouseClicked
        if(jMCancelar.isEnabled()){
            limpaCampos();
            statusTela(VISUALIZAR);
        }
    }//GEN-LAST:event_jMCancelarMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMCancelar;
    private javax.swing.JMenu jMEditar;
    private javax.swing.JMenu jMExcluir;
    private javax.swing.JMenu jMLimpar;
    private javax.swing.JMenu jMNovo;
    private javax.swing.JMenu jMSalvar;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField jTCategoria;
    // End of variables declaration//GEN-END:variables

    private void statusTela(int status) {
        if (status == VISUALIZAR) {
            this.status = VISUALIZAR;
            jMNovo.setEnabled(true);
            jMSalvar.setEnabled(false);
            jMEditar.setEnabled(false);
            jMExcluir.setEnabled(false);
            jMLimpar.setEnabled(false);
            jMCancelar.setEnabled(false);
            tblCategorias.setEnabled(true);
            linhaSelecionada = -1;
            tblCategorias.getSelectionModel().clearSelection();
//            jLTotFuncionarios.setText(String.valueOf(tblCategorias.getRowCount()));
            limpaCampos();
        } else if (status == ADCIONAR) {
            this.status = ADCIONAR;
            jMNovo.setEnabled(false);
            jMSalvar.setEnabled(true);
            jMEditar.setEnabled(false);
            jMExcluir.setEnabled(false);
            jMLimpar.setEnabled(true);
            jMCancelar.setEnabled(true);
            tblCategorias.setEnabled(false);
        } else if (status == EDITAR) {
            this.status = EDITAR;
            jMNovo.setEnabled(false);
            jMSalvar.setEnabled(true);
            jMEditar.setEnabled(false);
            jMExcluir.setEnabled(true);
            jMLimpar.setEnabled(true);
            jMCancelar.setEnabled(true);
            tblCategorias.setEnabled(false);
        } else if (status == SELECIONAR) {
            this.status = SELECIONAR;
            jMNovo.setEnabled(true);
            jMSalvar.setEnabled(false);
            jMEditar.setEnabled(true);
            jMExcluir.setEnabled(true);
            jMLimpar.setEnabled(false);
            jMCancelar.setEnabled(false);

        }
        statusCampos(status);
    }

    private void statusCampos(int status) {
        if (status == VISUALIZAR) {

            jTCategoria.setEditable(false);
            
        } else if (status == EDITAR) {

            jTCategoria.setEditable(true);
            
        } else if (status == ADCIONAR) {

            jTCategoria.setEditable(true);
            
        }
        jMNovo.requestFocus();
    }

    private void limpaCampos() {

        jTCategoria.setText("");
        

    }

    private void getListaCategoriaes() {

        categorias = new CategoriaController().listar();

    }

    //METODOS DA TABELA
    private void montaTabela() {
        getListaCategoriaes();
        System.out.println(categorias.size());
        jPanel3.add(getTblCategoriaes());
        scrollPane.setBounds(5, 20, jPanel3.getWidth() - 10, jPanel3.getHeight() - 25);
    }

    private JScrollPane getTblCategoriaes() {
        if (tblCategorias == null) {
            tblCategorias = new JTable();
            // permite selecionar apenas uma linha de cada vez
            tblCategorias.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            tblCategorias.setDefaultRenderer(String.class, new CellRenderer());

            tblCategorias.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent me) {
                    //        System.out.println(linhaSelecionada);
                    if ((me.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) {
                        if (tblCategorias.isEnabled()) {

                            if (status == VISUALIZAR) {
                                statusTela(SELECIONAR);

                            }
                        }
                    } else if ((me.getModifiers() & MouseEvent.BUTTON2_MASK) != 0) {
                        JOptionPane.showMessageDialog(null, "Isso não é algo Legal!");
                    } else if ((me.getModifiers() & MouseEvent.BUTTON3_MASK) != 0) {
                        JPopupMenu menu = new JPopupMenu();
                        JMenuItem cliqueme = new JMenuItem("Copiar");
                        int col = tblCategorias.columnAtPoint(me.getPoint());
                        int row = tblCategorias.rowAtPoint(me.getPoint());
                        cliqueme.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                copyClipboard(String.valueOf(tableModel.get(row, col)));
                            }
                        });

                        menu.add(cliqueme);

                        menu.show(tblCategorias, me.getX(), me.getY());
                    }
                }

            });
            tblCategorias.setModel(getTableModel());
            defineRenderers();
            scrollPane = new JScrollPane(tblCategorias);
        }
        return scrollPane;
    }

    private CategoriaTable getTableModel() {
        if (tableModel == null) {
            tableModel = new CategoriaTable(categorias);

        }
        return tableModel;
    }

    private void defineRenderers() {
//        DefaultTableCellRenderer rendererCentro = new DefaultTableCellRenderer();
//        rendererCentro.setHorizontalAlignment(SwingConstants.CENTER);
//        DefaultTableCellRenderer rendererDireita = new DefaultTableCellRenderer();
//        rendererDireita.setHorizontalAlignment(SwingConstants.RIGHT);
//        DefaultTableCellRenderer rendererEsquerda = new DefaultTableCellRenderer();
//        rendererEsquerda.setHorizontalAlignment(SwingConstants.LEFT);

        JTableHeader header = tblCategorias.getTableHeader();
        header.setPreferredSize(new Dimension(0, 35));
        TableColumnModel modeloDaColuna = tblCategorias.getColumnModel();
        int[] tam = {35, 1000};

        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            modeloDaColuna.getColumn(i).setMaxWidth(tam[i]);
            modeloDaColuna.getColumn(i).setCellRenderer(new TooltipCellRender());

        }

    }

    private void copyClipboard(String texto) {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        StringSelection selection = new StringSelection(texto);
        clipboard.setContents(selection, null);
    }
    
}
